package com.saishi.dao.impl;

import com.saishi.dao.BookDao;
import com.saishi.entity.Book;
import com.saishi.util.AliPool;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDaoImpl implements BookDao {
    QueryRunner qr = new QueryRunner(AliPool.getDs());

    @Override
    public List<Book> allQuery() throws SQLException {
        String sql = "SELECT * FROM `book`";
        return qr.query(sql, new BeanListHandler<Book>(Book.class));
    }

    @Override
    public Book query(int bookid) throws SQLException {
        String sql = "SELECT * FROM `book` where bookid = ?;";
        return qr.query(sql, new BeanHandler<Book>(Book.class), bookid);
    }

    @Override
    public int insert(Book book) throws SQLException {
        String sql = "INSERT INTO `book` VALUES (null, ?, ?);";
        return qr.update(sql, book.getBookname(), book.getBookdesc());
    }

    @Override
    public int update(Book book) throws SQLException {
        String sql = "UPDATE `book` SET `bookname` = ?, `bookdesc` = ? WHERE `bookid` = ?;";
        return qr.update(sql, book.getBookname(), book.getBookdesc(), book.getBookid());
    }

    @Override
    public int delete(int bookid) throws SQLException {
        String sql = "DELETE FROM `book` WHERE `bookid` = ?;";
        return qr.update(sql, bookid);
    }
}
